<template>
  <div class="add-model">
    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="dialogFormVisible" :modal-append-to-body='false' :before-close="onclickClose" top="50px" :width="'90%'">
      <div class="add-div">
        <el-row class="height">
          <el-col :span="6" class="height left">
            <!-- 服务列表 -->
            <div class="title">服务列表</div>
            <service-list @serviceCall="serviceCall" />
          </el-col>
          <el-col :span="7" class="height right">
            <!-- 接口列表 -->
            <interface-list v-if="isSiId" :si-id="siId" @dragCall="dragCall" :disabled="type >= 2"/>
          </el-col>
          <el-col :span="11" class="data-form">
            <div class="title">任务信息</div>
            <el-form ref="form" :model="form" label-width="80px" size="mini">
              <el-form-item label="任务名称" prop="name" :rules="[{ required: true, message: '请输入任务名称', trigger: 'blur' }]">
                <el-input :disabled="type >= 2" v-model.trim="form.name" :maxLength="20"></el-input>
              </el-form-item>

              <el-form-item label="备注" style="margin:20px 0" prop="remark">
                <el-input :disabled="type >= 2" type="textarea" :rows="5"  v-model="form.remark" :maxLength="200"></el-input>
              </el-form-item>

              <el-form-item label="关系图">
                <div class="echarts-item">
                  <jtopo v-if="isJtopo" :disabled="type >= 2" @clickNodeCall="clickNodeCall" @clearAllCall="clearAllCall" :node-list="addAllData.nodeArr"/>
                </div>
              </el-form-item>
              <el-form-item class="dialog-footer" v-if="type < 2" style="text-align:right;margin-top:20px">
                <el-button type="primary" @click="addServerData">
                  <span v-if="type === 0">保 存</span>
                  <span v-else>保存修改</span>
                </el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
      </div>
    </el-dialog>

    <!-- 接口配置 -->
    <el-dialog title="接口配置" :close-on-press-escape="true" top="50px" :before-close="beforeCloseInterface" :visible.sync="interfaceConfigDialog" :width="'90%'" :modal-append-to-body='false'>
      <div style="padding:20px;">
        <interface-config
          ref="interfaceConfig"
          v-if="isInterFaceConfig"
          :node="node"
          :disabled="type >= 2"
          :dataType="dataType"/>
        <div style="text-align:right;margin-top:10px;" v-if="type < 2">
          <el-button type="primary" size="mini" @click="saveInterface">保存</el-button>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<script>
    import ServiceList from "./ServiceList"
    import InterfaceList from "./InterfaceList"
    import Jtopo from "../../compoents/Jtopo"
    import InterfaceConfig from "./InterfaceConfig"
    let CircularJSON = require('circular-json');
    export default {
      components:{
        ServiceList, InterfaceList, InterfaceConfig, Jtopo
      },
      name: "addOrUpdateTask",
      props: {
        //是否显示弹窗
        dialog: {
          type: Boolean
        },
        //判断0：添加，1：修改，2详情
        type: {
          type: Number,
          default: 0
        },
        //详情信息
        detail: {
          type: Object,
          required: false
        }
      },
      data () {
        return {
          dialogFormVisible: false,
          form: { name: '', remark: '' },
          title: '',
          siId: null,                   //实例ID
          isSiId: true,                 //作为刷新ID使用
          node: null,                   //接口对象
          isInterFaceConfig: true,      //用于刷新组件
          interfaceConfigDialog: false, //接口配置弹窗
          isUpdate: false,              //数据是否回显  true时回显
          dataType: this.type,
          isJtopo: true,                //刷新关系图组件
          addAllData: {},               // 保存数据结构
        }
      },
      created () {
        //避免脏数据
        this.$store.commit("nodeList", []);
        switch (this.type) {
          case 0: this.title = "新增任务"; break;
          case 1: this.title = "修改任务"; break;
          default: this.title = "查看任务"; break;
        }
        this.dialogFormVisible = this.dialog;
        if (Object.keys(this.detail).length > 0) {
          console.log("detail: ", this.detail);
          //填充数据
          this.form.name = this.detail.taskName;
          this.form.remark = this.detail.remark;
          this.addAllData = this.detail;
          // TODO 服务ID|实例ID
        }
      },
      beforeDestroy() {
        //清空缓存
        this.$store.commit("nodeList", []);
      },
      methods: {
        /**关闭新增第一层弹窗**/
        onclickClose(done){
          this.$emit("closeCall");
          if (done) {
            done();
          }
        },
        /**关闭接口配置弹窗回调**/
        beforeCloseInterface (done) {
          this.isInterFaceConfig = false;
          this.interfaceConfigDialog = false;
          if (done) {
            done();
          }
        },
        /**选择服务实例回调**/
        serviceCall (sid) {
          this.sid = sid;
          this.isSiId = false;
          this.$nextTick(() => {
            this.isSiId = true;
          })
        },
        /**拖拽回调**/
        dragCall(row) {
          console.log("拖拽：", row);
          row.sId = this.sid;
          this.axios.get(this.baseApi.path + '/center/getUUID').then(res => {
            row.nodeId = res.data;
            this.$store.commit("interfaceNode", JSON.parse(JSON.stringify(row)));
          });
        },
        /**单击节点回调函数**/
        clickNodeCall(data) {
          //1.筛选父节点
          let parentInterfaceList = [];
          if (data.inLinks) {
            data.inLinks.forEach(item => {
              parentInterfaceList.push(item.nodeA);
            })
          }
          this.$store.commit("parentInterfaceList", parentInterfaceList);
          //2.作为点击保存的时候判断是修改的那一个对象
          this.nodeId = data.nodeId;
          this.node = data.interfaceNode;
          this.isInterFaceConfig = false;
          this.$nextTick(() => {
            this.isInterFaceConfig = true;
            this.interfaceConfigDialog = true;
          })
        },
        /**配置参数信息**/
        saveInterface() {
          //1.获取inHeader、inQuery
          let paramsJson = this.$refs.interfaceConfig.getParamsJson();
          //2.获取inBody
          let interfaceJson = this.$refs.interfaceConfig.getInterfaceJson();
          //3.获取断言条件
          let assert = this.$refs.interfaceConfig.getAssert();
          //更新缓存里面的数据
          let nodeList = this.$store.getters.nodeList;
          for (let i = 0; i < nodeList.length; i++) {
            let item = nodeList[i].interfaceNode;
            if (nodeList[i].elementType === "node" && nodeList[i].nodeId === this.nodeId) {
              item.updateInterfaceJson = interfaceJson;
              item.updateParamsJson = paramsJson;
              item.updateAssertJson = assert;
              break;
            }
          }
          this.$store.commit("nodeList", nodeList);
          //关闭弹窗
          this.beforeCloseInterface();
        },
        /**获取组装好的node数据结构，用于还原**/
        getNodeList() {
          let nodeList = [], nodeArr = [], vuexNodeList = this.$store.getters.nodeList;
          vuexNodeList.forEach(item => {
            if (item.elementType === "node") {
              nodeList.push(item);
            }
          });
          nodeList.forEach(item => {
            let parents = [], children = [];
            //查找父节点
            if (item.inLinks) {
              item.inLinks.forEach(out => {
                parents.push({
                  interfaceNode: out.nodeA.interfaceNode
                });
              });
            }
            //查找子节点
            if (item.outLinks) {
              item.outLinks.forEach(out => {
                children.push({
                  interfaceNode: out.nodeZ.interfaceNode
                });
              });
            }
            nodeArr.push({
              parents, children,
              nodeId: item.nodeId,
              interfaceNode: item.interfaceNode,
              x: item.x,
              y: item.y
            })
          });
          return nodeArr;
        },
        /**获取组装好的后台需要的节点数据结构**/
        getInterfaces() {
          let nodeList = [], nodeArr = [], vuexNodeList = this.$store.getters.nodeList;
          vuexNodeList.forEach(item => {
            if (item.elementType === "node") {
              nodeList.push(item);
            }
          });
          nodeList.forEach(item => {
            let parents = [], children = [];
            //查找父节点
            if (item.inLinks) {
              item.inLinks.forEach(out => {
                parents.push(out.nodeA.interfaceNode.nodeId);
              });
            }
            //查找子节点
            if (item.outLinks) {
              item.outLinks.forEach(out => {
                children.push(out.nodeZ.interfaceNode.nodeId);
              });
            }
            nodeArr.push({
              parents, children,
              nodeId: item.nodeId,
              interfaceId: item.interfaceNode.siaId,
              interfaceName: item.interfaceNode.siaName,
              instanceId: item.interfaceNode.siId,
              serverId: item.interfaceNode.sId,
              paramsData: {
                inBody: item.interfaceNode.updateInterfaceJson ? CircularJSON.stringify(item.interfaceNode.updateInterfaceJson) : "",
                inHeader: item.interfaceNode.updateParamsJson ? CircularJSON.stringify(item.interfaceNode.updateParamsJson.inHeader) : "",
                inQuery: item.interfaceNode.updateParamsJson ? CircularJSON.stringify(item.interfaceNode.updateParamsJson.inQuery) : "",
                outValue: item.interfaceNode.siaResponseData
              },
              assertConditions: [
                {
                  conditions: CircularJSON.stringify(item.interfaceNode.updateAssertJson)
                }
              ]
            })
          });
          return nodeArr;
        },
        /**添加任务**/
        addServerData() {
          if (this.getInterfaces().length === 0) {
            this.$message({ type: 'warning', message: '请添加接口配置信息' });
            return;
          }
          this.$refs["form"].validate((valid) => {
            if (valid) {
              this.addAllData.taskName = this.form.name;
              this.addAllData.remark = this.form.remark;
              this.addAllData.nodeArr = JSON.stringify(this.getNodeList());
              this.addAllData.interfaces = this.getInterfaces();
              console.log(this.addAllData);
              let url = "/task/add";
              if (this.addAllData.taskId) {
                url = "/task/modify";
              }
              this.$http.post(url, this.addAllData)
                .then(res => {
                  this.$store.commit("nodeList", []);
                  this.onclickClose();
                  if (this.addAllData.taskId) {
                    this.$notify.success("修改成功");
                  }
                  else {
                    this.$notify.success("添加成功");
                  }
                })
            }
          });
        },
        /**全部清空回调**/
        clearAllCall() {
          this.addAllData = {}
          this.$store.commit("nodeList", []);
          this.isJtopo = false;
          this.$nextTick(() => {
            this.isJtopo = true;
          })
        }
      }
    }
</script>

<style>
  .add-model .title{
    color: #333;
    font-weight: 600;
    padding: 15px 15px;
    box-sizing: border-box;
  }
  .height{
    height: 100%;
  }
</style>
<style scoped lang="less">
  .add-div{
    height: 800px;
    overflow-y: auto;
    .left{
      position:relative;
      border-right: 1px solid #e5e5e5;
    }
    .right {
      position: relative;
      border-right: 1px solid #e5e5e5;
    }
  }
  .data-form{
    padding: 0 15px;
  }
  .echarts-item{
    height: 500px;
    width: 100%;
    border:1px solid #dcdfe6;
    border-radius: 4px;
    background: #eee;
  }
</style>
